package netmon.gui;

import java.text.DecimalFormat;
import java.util.TimerTask;

import netmon.snmp.OIDConverter;
import netmon.snmp.SNMPEngine;

/**
 * TimerTask which is run every second. It is needed to update the continously changing elements in the GUI.
 * @author Marc Backes
 */
public class UpdateGUITT extends TimerTask {
	private static int secondsToSpeedUpdate = 20;		// Seconds after how many the transfer rate is updated
	private SNMPEngine snmpE = new SNMPEngine();		// Reference to the SNMP facade
	private OIDConverter oiC = new OIDConverter();		// Reference to the SNMP OID converter
	private NetmonGUIController guiC;					// Reference to the Graphical User Interface
	
	private boolean ready = false;						// Variable to tell if the class should be ready (acting) or not						
	private long receivedLastIn; 						// Last received value of 'ifInOctets'
	private long receivedLastOut;						// Last received value of 'ifInOctets'
	private int numOfSeconds = 1;						// Number of seconds already passed

	/**
	 * Initializing
	 * @param guiC Reference to the GUI Controller
	 */
	public UpdateGUITT(NetmonGUIController guiC) {
		this.guiC = guiC;
	}

	/**
	 * Method is run every second (by <i>refreshTimer</i> in <i>NetmonGUIController</i>)
	 */
	public void run() {		
		if(ready){
			/* Download speed */
			if (numOfSeconds == secondsToSpeedUpdate) { // Update every <secondsToSpeedUpdate> seconds
				/* Retreive the current data */
				int receivedNowIn = snmpE.getIntById(oiC.get("ifInOctets")+ "." + guiC.getInterfaceNumber());
				int receivedNowOut = snmpE.getIntById(oiC.get("ifOutOctets")+ "." + guiC.getInterfaceNumber());
				
				/* Calculate the difference */
				double transferRateIn = (double) ((receivedNowIn - receivedLastIn) / 1000) / secondsToSpeedUpdate;
				double transferRateOut = (double) ((receivedNowOut - receivedLastOut) / 1000) / secondsToSpeedUpdate;
				
				/* Update the GUI with the new calculated data */
				DecimalFormat df = new DecimalFormat("#.##");
				guiC.refreshTransferRates(df.format(transferRateIn) + " kB/s", df.format(transferRateOut) + " kB/s");

				numOfSeconds = 1;	// Setting back to second 1
				
				// "Next last received" = Now received
				receivedLastIn = receivedNowIn;
				receivedLastOut = receivedNowOut;
			} else {
				numOfSeconds++;
			}
			/* Update the data in the GUI needed to be updated every second */
			guiC.continouslyRefresh();
		}
	}

	/**
	 * Set the ready status of the class
	 * @param ready Ready status
	 */
	void setReady(boolean ready){
		this.ready = ready;
		receivedLastIn = (long)snmpE.getIntById(oiC.get("ifInOctets")+"."+guiC.getInterfaceNumber());
		receivedLastOut = (long)snmpE.getLongById(oiC.get("ifOutOctets")+"."+guiC.getInterfaceNumber());
		guiC.resetBars();
	}
}
